new Vue({
    el: '#app',
    data: {
        products: [],
        activeCategory: 0, // 默认全部，使用数字ID
        categories: [], // 分类列表
        userAvatarUrl: '', // 用户头像URL
        username: '' // 用户名
    },
    methods: {
        // 获取所有分类
        findAllClassfiy() {
            $.ajax({
                url: 'http://localhost:8080/index/findAllClassify',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: response => {
                    if (response.code === 200) {
                        this.categories = response.data;
                        // 默认选中第一个分类
                        if (this.categories.length > 0) {
                            this.activeCategory = this.categories[0].id;
                            this.fetchProducts(this.activeCategory);
                        }
                    } else {
                        console.error('加载分类失败：' + response.message);
                    }
                },
                error: response => {
                    console.error('加载分类失败：' + response.message);
                }
            })
        },
        // 分类切换
        filterCategory(categoryId) {
            this.activeCategory = categoryId;
            this.fetchProducts(categoryId);
        },

        // 获取商品列表
        fetchProducts(categoryId = 0) {
            $.ajax({
                url: 'http://localhost:8080/index/findAll',
                type: 'GET',
                data: { categoryId: categoryId },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                dataType: 'json',
                success: (response) => {
                    console.log(response);
                    if (response.code === 200) {
                        this.products = response.data;
                        this.products.forEach(product => {
                            // 处理商品图片路径
                            if (product.commodityPicture && product.commodityPicture.length > 0) {
                                product.image = '\\' + product.commodityPicture[0].commodityImageUrl.match(/photo[\\\\/].+$/)[0];
                            } else {
                                product.image = ''; 
                            }
                        });
                    } else {
                        this.products = [];
                        console.error('加载商品失败：' + response.message);
                    }
                },
                error: () => {
                    this.products = [];
                    console.error('加载商品失败，请稍后重试');
                }
            });
        },

        // 搜索商品
        searchProducts(keyword) {
            if (!keyword.trim()) {
                this.fetchProducts(this.activeCategory);
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/commodity/search',
                method: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    keyword: keyword,
                    categoryId: this.activeCategory
                },
                success: (response) => {
                    if (response.code === 200) {
                        this.products = response.data;
                        this.products.forEach(product => {
                            // 处理商品图片路径
                            if (product.commodityPicture && product.commodityPicture.length > 0) {
                                product.image = '\\' + product.commodityPicture[0].commodityImageUrl.match(/photo[\\\\/].+$/)[0];
                            } else {
                                product.image = ''; 
                            }
                        });
                    } else {
                        this.products = [];
                        console.error('搜索失败：' + response.message);
                    }
                },
                error: () => {
                    this.products = [];
                    console.error('搜索请求失败，请稍后重试');
                }
            });
        },
        // 获取用户个人信息
        fetchUserInfo() {
            const token = localStorage.getItem('token') || ''; // 从本地存储获取token
            if (!token) {
                console.warn('未找到用户token，无法加载用户信息。');
                this.userAvatarUrl = '/photo/Profile picture/微信图片_20240927140746.jpg';
                this.username = '请登录';
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/user/findUserById',
                type: 'Post',
                dataType: 'json',
                headers: {
                    'token': token
                },
                data: {
                    userId: localStorage.getItem('userId') || ''
                },
                success: (response) => {
                    if (response.code === 200) {
                        this.username = response.data.userName;
                        this.userAvatarUrl = '/' + response.data.avatar.match(/photo[\\\\/].+$/)[0];
                        console.log(this.username);
                        console.log(this.userAvatarUrl);

                    }
                },
                error: function (xhr, status, error) {
                    console.error('加载用户信息失败:', error, xhr.responseText);
                    if (xhr.status === 401) {
                        // token过期或无效
                        logout(); // 调用 logout 函数清除存储并跳转
                    } else {
                        alert('加载用户信息失败，请稍后重试');
                    }
                }
            });
        },
        //点击退出跳转到登录页面
        logout() {
            localStorage.removeItem('token'); // 删除token
            localStorage.removeItem('userId'); // 删除userId
            window.location.href = '/login.html'; // 跳转到登录页面
        }
    },
    created() {
        // 页面加载时获取商品列表
        this.fetchProducts(0);
        // 页面加载时获取分类列表
        this.findAllClassfiy();
        // 页面加载时获取用户个人信息
        this.fetchUserInfo();
    },
    mounted() {
        // 搜索功能
        const searchInput = $('#searchInput');
        const searchButton = $('#searchButton');

        // 搜索按钮点击
        searchButton.on('click', (e) => {
            e.preventDefault();
            this.searchProducts(searchInput.val().trim());
        });

        // 回车搜索
        searchInput.on('keypress', (e) => {
            if (e.which === 13) {
                e.preventDefault();
                this.searchProducts(searchInput.val().trim());
            }
        });

    }
});

// 轮播图功能
$(document).ready(function () {
    const carousel = {
        currentIndex: 0,
        timer: null,
        isHovered: false,
        wrapper: $('.carousel-wrapper'),
        slides: $('.carousel-slide'),
        dots: $('.dot'),
        prevBtn: $('.carousel-btn.prev'),
        nextBtn: $('.carousel-btn.next'),
        container: $('.carousel-container'),

        init() {
            this.bindEvents();
            this.startAutoPlay();
        },

        bindEvents() {
            // 鼠标悬停事件
            this.container.on('mouseenter', () => {
                this.isHovered = true;
                this.stopAutoPlay();
            }).on('mouseleave', () => {
                this.isHovered = false;
                this.startAutoPlay();
            });

            // 按钮点击事件
            this.prevBtn.on('click', () => this.prevSlide());
            this.nextBtn.on('click', () => this.nextSlide());

            // 圆点点击事件
            this.dots.each((index, dot) => {
                $(dot).on('click', () => this.goToSlide(index));
            });
        },

        startAutoPlay() {
            this.stopAutoPlay(); // 先清除已有定时器，防止重复绑定
            if (!this.isHovered) {
                this.timer = setInterval(() => this.nextSlide(), 2500);
            }
        },

        stopAutoPlay() {
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        },

        updateSlide() {
            this.wrapper.css('transform', `translateX(-${this.currentIndex * 100}%)`);
            this.dots.removeClass('active').eq(this.currentIndex).addClass('active');
        },

        nextSlide() {
            this.currentIndex = (this.currentIndex + 1) % this.slides.length;
            this.updateSlide();
        },

        prevSlide() {
            this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
            this.updateSlide();
        },

        goToSlide(index) {
            this.currentIndex = index;
            this.updateSlide();
        }
    };

    // 初始化轮播图
    carousel.init();
}); 